<?php
/**
 *备货日志控制器
 *@author shipanpan
 */
class Backup_LogController extends Controller_NeedLogin {

	/**
	 * 备货日志列表
	 * @return [type] [description]
	 */
	public function listAction() {
		$this->db = Model_Db::getInstance();
		$queryParameter = $this->getRequest()->getQuery();
		$where = "";
		if ($queryParameter['goods_sn'] ?? '') {
			$where .= "AND " . $this->db->quoteInto("goods_sn in (?)", explode(',', $queryParameter['goods_sn'])) . " ";
		}
		if ($queryParameter['warehouse'] ?? '') {
			$where .= "AND " . $this->db->quoteInto("log.warehouse=?", $queryParameter['warehouse']) . " ";
		}
		if ($queryParameter['start_date'] ?? '') {
			$where .= "AND " . $this->db->quoteInto("create_date>=?", $queryParameter['start_date']) . " ";
		}
		if ($queryParameter['end_date'] ?? '') {
			$where .= "AND " . $this->db->quoteInto("create_date<=?", $queryParameter['end_date']) . " ";
		}
		$querySql = "select %fields% from b_product_backup_log as log left join b_product_backup_rule as rule on log.c_story_use_rule_id=rule.id left join c_warehouse  as warehouse on log.warehouse=warehouse.warehouse_code";
		if ($where) {
			$where = ltrim($where, 'AND');
			$querySql .= " where $where";
		}

		$countField = "count(*)";
		$countSql = str_replace("%fields%", $countField, $querySql);

		$amount = $this->db->fetchOne($countSql);

		$pageLink = "";
		$backupLogList = [];
		if ($amount) {
			$queryField = "log.*,rule.name,rule.avg_sales_formula_type,warehouse.warehouse_name";
			$querySql = str_replace("%fields%", $queryField, $querySql);
			$page = (int) ($this->getRequest()->getParam('page') ?? 1);
			$pageLength = (int) $this->page_size;

			$limitSql = " limit " . ($page - 1) * $pageLength . "," . $pageLength;
			$querySql .= $limitSql;
			$backupLogList = $this->db->fetchAll($querySql);
			$pageLink = $this->page($amount, $pageLength);
		}

		$this->smarty->assign('page_link', $pageLink);
		$this->smarty->assign('backupLogList', $backupLogList);
		$this->smarty->assign("queryParameter", $queryParameter);
		$this->smarty->display('backupLogList.tpl');
	}

	/**
	 * 获取需求A(缺货需求)的备货日志
	 * @return [type] [description]
	 */
	public function aStoryAction() {
		$productAStoryLog = $this->_search();
		if ($productAStoryLog && $productAStoryLog['has_calculate_a_story']) {
			//需求a未出原因
			$notHaveAStoryReason = "";

			$productCatalogModel = new Application_Model_ProductCatalog();
			$productCatalogInfo = $productCatalogModel->getDetailById($productAStoryLog['product_catalog'], ['name_ch']);
			$productAStoryLog['productCatalogName'] = $productCatalogInfo['name_ch'] ?? "";
			$stockoutStoryModel = new Application_Model_StockoutStory();
			$productAStoryLog['productCatalogCheckFail'] = $stockoutStoryModel->isForbidProductCatalog($productAStoryLog['product_catalog']);
			if ($productAStoryLog['productCatalogCheckFail']) {
				$notHaveAStoryReason .= "，产品分类为" . $productAStoryLog['productCatalogName'];
			}

			$productGradeModel = new Application_Model_ProductGrade();
			$productAStoryLog['productGradeName'] = $productGradeModel->getName($productAStoryLog['product_grade']);
			$productAStoryLog['productGradeCheckFail'] = $stockoutStoryModel->isForbidProductGrade($productAStoryLog['product_grade']);
			if ($productAStoryLog['productGradeCheckFail']) {
				$notHaveAStoryReason .= "，产品等级为" . $productAStoryLog['productGradeName'];
			}

			$productAStoryLog['productResourceStatusName'] = Application_Model_Product::RESOURCE_STATUS[$productAStoryLog['resource_status']];
			$productAStoryLog['productResourceStatusCheckFail'] = $stockoutStoryModel->isForbidProductResourceStatus($productAStoryLog['resource_status']);
			if ($productAStoryLog['productResourceStatusCheckFail']) {
				$notHaveAStoryReason .= "，产品货源状态为:" . $productAStoryLog['productResourceStatusName'];
			}

			if ($productAStoryLog['a_story_is_intercept']) {
				$notHaveAStoryReason .= "，需求被拦截";
			}
			if ($notHaveAStoryReason) {
				$notHaveAStoryReason = "产品" . $productAStoryLog['goods_sn'] . '，因为' . ltrim($notHaveAStoryReason, '，') . ";所以未出A需求！";
			}
			$productAStoryLog['notHaveAStoryReason'] = $notHaveAStoryReason;
		}
		$departmentModel = new Application_Model_Department();
		$hasWarehouseDep = $departmentModel->hasWarehouse();
		$this->smarty->assign('hasWarehouseDep', $hasWarehouseDep);
		$this->smarty->assign('productAStoryLog', $productAStoryLog);
		$this->smarty->display('aStoryLogDetail.tpl');
	}

	/**
	 * 需求c检测(获取需求c备货日志详情)
	 * @return [type] [description]
	 */
	public function cStoryAction() {
		$productCStoryLog = $this->_search();
		if ($productCStoryLog) {
			$backupRuleModel = new Backup_Model_BackupRule();
			if ($productCStoryLog['c_story_use_rule_id']) {
				$backupRuleInfo = $backupRuleModel->getOne($productCStoryLog['c_story_use_rule_id']);
				$productCStoryLog['backupRuleName'] = $backupRuleInfo['name'] ?? '';
				$productCStoryLog['meanSalesFormulaDescription'] = Backup_Model_SalesMeanStrategy::description($backupRuleInfo['avg_sales_formula_type']);
			}

			//备货数量是否低于最小备货量
			$productCStoryLog['less_than_story_min_quantity'] = false;
			//如果备货数量在“最小备货量”检查项前不为0，检查后为0，表示备货数量是小于最小备货量的
			if ($productCStoryLog['after_min_limit_c_story_quantity'] == 0 && $productCStoryLog['after_a_story_limit_c_story_quantity']) {
				$productCStoryLog['less_than_story_min_quantity'] = true;
			}

			//备货数量是否大于最大备货量
			$productCStoryLog['greater_than_story_max_quantity'] = false;
			//如果备货数量在“最小备货量”检查后的值大于最大备货量，表示备货数量是大于最大备货量的
			if ($productCStoryLog['after_min_limit_c_story_quantity'] > $productCStoryLog['c_story_max_quantity']) {
				$productCStoryLog['greater_than_story_max_quantity'] = true;
			}

			//商品备货总数量是否小于最小起订量
			$productCStoryLog['less_than_min_order'] = false;
			//如果备货数量在“最大备货量”检查后的值不等于如果备货数量在“最小起订量”检查项后的值，表示备货数量因为最小起订量限制发生变化了
			if ($productCStoryLog['product_min_order']) {
				$productCStoryLog['less_than_min_order'] = ($productCStoryLog['after_max_limit_c_story_quantity'] != $productCStoryLog['after_min_order_limit_c_story_quantity']) ? true : false;
			}

			if ($packageNum = $productCStoryLog['product_package_quantity']) {
				$backupQuantityRemainder = ($productCStoryLog['after_min_order_limit_c_story_quantity']) % $packageNum;
				if ($backupQuantityRemainder <= 0.09 * $packageNum) {
					$productCStoryLog['packageNumRemainder'] = "$backupQuantityRemainder<=9%";
				} elseif ($backupQuantityRemainder >= 0.9 * $packageNum) {
					$productCStoryLog['packageNumRemainder'] = "$backupQuantityRemainder>=90%";
				} else {
					$productCStoryLog['packageNumRemainder'] = '9%<' . $backupQuantityRemainder . '<90%';
				}
			}
			//如果备货数量在“商品备货总数”检查后的值不等于如果备货数量在“整箱数”检查项后的值，表示备货数量因为“商品备货总数”限制发生变化了
			$productCStoryLog['greater_than_product_backup_amount'] = false;
			if ($productCStoryLog['after_package_quantity_c_story_quantity'] > $productCStoryLog['after_backup_amount_c_story_quantity']) {
				$productCStoryLog['greater_than_product_backup_amount'] = true;
			}

			//检测结果描述
			$checkResultDescription = '产品';
			if ($productCStoryLog['c_story_fail_remark']) {
				$productCStoryLog['c_story_check_description'] = $checkResultDescription . ',因为' . $productCStoryLog['c_story_fail_remark'] . ',不满足产生需求C的要求，因此没有产生需求C;';
			} elseif ($productCStoryLog['c_story_quantity_modify_remark']) {
				if ($productCStoryLog['c_story_use_rule_id']) {
					$productCStoryLog['c_story_check_description'] = $checkResultDescription . '满足产生需求C的要求，但' . $productCStoryLog['c_story_quantity_modify_remark'];
				} else {
					$productCStoryLog['c_story_check_description'] = $checkResultDescription . $productCStoryLog['c_story_quantity_modify_remark'];
				}

			} else {
				$productCStoryLog['c_story_check_description'] = $checkResultDescription . '满足产生需求C的要求，并且需求C=' . $productCStoryLog['after_backup_amount_c_story_quantity'];
			}

		}
		$departmentModel = new Application_Model_Department();
		$hasWarehouseDep = $departmentModel->hasWarehouse();
		$this->smarty->assign('hasWarehouseDep', $hasWarehouseDep);
		$this->smarty->assign('productCStoryLog', $productCStoryLog);
		$this->smarty->display('cStoryLogDetail.tpl');
	}

	/**
	 * 备货日志搜索
	 * @return [type] [description]
	 */
	private function _search() {
		$queryParameter = $this->getRequest()->getQuery();
		$this->db = Model_Db::getInstance();

		$goodsSn = $queryParameter['goods_sn'] ?? false;
		$warehouse = $queryParameter['warehouse'] ?? false;
		$logCreateDate = $queryParameter['date'] ?? date("Y-m-d");

		$queryWhere = $this->db->quoteInto("backup_log.goods_sn=?", $goodsSn) . " ";
		$warehouse && $queryWhere .= "AND " . $this->db->quoteInto("backup_log.warehouse=?", $warehouse) . " ";
		$logCreateDate && $queryWhere .= "AND " . $this->db->quoteInto("backup_log.create_date=?", $logCreateDate);

		return $this->db->fetchRow('select product.product_name,goods_name,product.thumb_url,backup_log.* from p_product as product left join  b_product_backup_log as backup_log on product.goods_sn=backup_log.goods_sn where ' . $queryWhere);
	}
}